package com.shqcjd.sinopecdemomobile.ui.activity.tipwizard;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.app.AppConstant;
import com.shqcjd.sinopecdemomobile.app.MyApp;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.eventbus.RefreshData;
import com.shqcjd.sinopecdemomobile.model.pojo.AppOperationGuideMode;
import com.shqcjd.sinopecdemomobile.model.pojo.QRScanBean;
import com.shqcjd.sinopecdemomobile.model.pojo.RouteQueryBean;
import com.shqcjd.sinopecdemomobile.model.pojo.TreeNode;
import com.shqcjd.sinopecdemomobile.ui.activity.FileListActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.GenerateQRcodeActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.RouteSpinnerAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.TipWizardListAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.TipWizardProgressAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.PrefUtils;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * 操作向导列表
 */
public class TipWizardListActivity extends BaseActivity {
    @BindView(R.id.rv_tip_wizard_list)
    RecyclerView rv_tip_wizard_list;
    @BindView(R.id.iv_toolbar_back)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.et_search)
    EditText editText;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.sr_inspection)
    SwipeRefreshLayout srInspection;
    @BindView(R.id.filter_btn)
    View filterSelect;
    @BindView(R.id.rl_pop)
    RelativeLayout rlPop;
    private View contentView;
    private String strSearch;
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多

    private List<AppOperationGuideMode.ItemsBean> adapterList = new ArrayList<>();

    private int total;
    private TipWizardListAdapter tipWizardListAdapter;


    private RouteSpinnerAdapter locationAdapter;//片区适配器
    private RouteSpinnerAdapter companyAdapter;//集团适配器
    private RouteSpinnerAdapter factoryAdapter;//工厂适配器
    private RouteSpinnerAdapter childAdapter;//分厂适配器
    private List<RouteQueryBean> locationList = new ArrayList<>();
    private List<RouteQueryBean> childList = new ArrayList<>();
    private List<RouteQueryBean> companyList = new ArrayList<>();
    private List<RouteQueryBean> factoryList = new ArrayList<>();
    ArrayList<TreeNode> backList = new ArrayList<>();

    private Context context;
    private String area = "";//片区
    private String branch_factory = "";//分厂
    private String factory = "";//厂
    private String group = "";//集团编号
    private int currentPos;
    private TipWizardProgressAdapter tipWizardProgressAdapter;
    private MaterialDialog showProgressDialog;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_tip_wizard_list;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        context = this;
        tvToolbarCenter.setText("向导视频知识库");
        tipWizardListAdapter = new TipWizardListAdapter();
        rv_tip_wizard_list.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
                try {
                    //try catch一下
                    super.onLayoutChildren(recycler, state);
                } catch (IndexOutOfBoundsException e) {

                }

            }
        });
        filterSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(rlPop);
            }
        });
        rv_tip_wizard_list.setAdapter(tipWizardListAdapter);
        ivToolbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                strSearch = editable.toString();
                refreshData();
            }
        });
        tipWizardListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                currentPos = position;
                switch (view.getId()) {
                    case R.id.tv_start_btn://开始操作
                        preShowProgressDialog(currentPos);
                        break;
                    case R.id.fl_generate_btn://生成二维码
                        showGenerateDialog(currentPos);
                        break;
                    case R.id.tv_file_btn://文件列表
                        AppOperationGuideMode.ItemsBean item = adapterList.get(currentPos);
                        Intent intent = new Intent(TipWizardListActivity.this, FileListActivity.class);
                        intent.putExtra("taskId", item.workTaskId);
                        startActivity(intent);
                        break;
                }
            }
        });

        tipWizardListAdapter.setNewData(adapterList);

        tipWizardListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                int pageSize = total % Config.PAGE_TOTAL == 0 ? total / Config.PAGE_TOTAL : total / Config.PAGE_TOTAL + 1;
                if (page >= pageSize || tipWizardListAdapter.getData().size() < Config.PAGE_TOTAL) {
                    rv_tip_wizard_list.post(new Runnable() {
                        @Override
                        public void run() {
                            tipWizardListAdapter.loadMoreEnd();
                        }
                    });
                } else {
                    loadMoreData();
                }
            }
        });

        srInspection.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
        getQueryLocationBean("area");
        refreshData();

    }


    private void showPopupWindow(ViewGroup view) {
        if (contentView != null) {
            contentView.setVisibility(View.VISIBLE);
            return;
        }
        contentView = LayoutInflater.from(view.getContext()).inflate(
                R.layout.pop_window, view, false);
        view.addView(contentView);

        RelativeLayout rl = contentView.findViewById(R.id.rl);
        LinearLayout ll_pop_content = contentView.findViewById(R.id.ll_pop_content);
        Spinner sp_pop_location = contentView.findViewById(R.id.sp_pop_location);
        Spinner sp_pop_child = contentView.findViewById(R.id.sp_pop_child);
        Spinner sp_pop_company = contentView.findViewById(R.id.sp_pop_company);
        Spinner sp_pop_factory = contentView.findViewById(R.id.sp_pop_factory);
        Button btn_pop_reset = contentView.findViewById(R.id.btn_pop_reset);
        Button btn_pop_commit = contentView.findViewById(R.id.btn_pop_commit);

        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentView.setVisibility(View.GONE);
            }
        });
        ll_pop_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        //重置
        btn_pop_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                companyList.clear();
                factoryList.clear();
                childList.clear();
                locationAdapter.notifyDataSetChanged();
                companyAdapter.notifyDataSetChanged();
                factoryAdapter.notifyDataSetChanged();
                childAdapter.notifyDataSetChanged();
                sp_pop_location.setSelection(0);
            }
        });

        //确定
        btn_pop_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                area = (locationList == null || locationList.isEmpty()) ? "" : locationList.get(sp_pop_location.getSelectedItemPosition()).code;
                group = (companyList == null || companyList.isEmpty()) ? "" : companyList.get(sp_pop_company.getSelectedItemPosition()).code;
                factory = (factoryList == null || factoryList.isEmpty()) ? "" : factoryList.get(sp_pop_factory.getSelectedItemPosition()).code;
                branch_factory = (childList == null || childList.isEmpty()) ? "" : childList.get(sp_pop_child.getSelectedItemPosition()).code;
                refreshData();
                contentView.setVisibility(View.GONE);
            }
        });


        sp_pop_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (locationList.get(position).code.isEmpty()) {
                    return;
                }
                getQueryCompanynBean(locationList.get(position).code);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_company.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getQueryFactoryBean(companyList.get(position).code);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_factory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getQueryChildBean(factoryList.get(position).code);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_child.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        locationAdapter = new RouteSpinnerAdapter(context, locationList);
        childAdapter = new RouteSpinnerAdapter(context, childList);
        companyAdapter = new RouteSpinnerAdapter(context, companyList);
        factoryAdapter = new RouteSpinnerAdapter(context, factoryList);
        sp_pop_location.setAdapter(locationAdapter);
        sp_pop_company.setAdapter(companyAdapter);
        sp_pop_factory.setAdapter(factoryAdapter);
        sp_pop_child.setAdapter(childAdapter);
    }

    private void getQueryCompanynBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            companyList.clear();
                            factoryList.clear();
                            childList.clear();
                            companyList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getQueryFactoryBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            factoryList.clear();
                            childList.clear();
                            factoryList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getQueryChildBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            childList.clear();
                            childList.add(new RouteQueryBean("", "", "全部"));
                            childList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


    private void refreshData() {
        refreshOrLoadMore();
        srInspection.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        adapterList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }

    private void refreshOrLoadMore() {
        if (tipWizardListAdapter != null) {
            tipWizardListAdapter.notifyLoadMoreToLoading();
        }
    }


    private void getData(int p) {
        String keyWord = strSearch == null ? "" : strSearch;
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", p + "");
        map.put("pageSize", Config.PAGE_TOTAL + "");
        map.put("area", area);
        map.put("branchFactory", branch_factory);
        map.put("equipmentTypeName", keyWord);
        map.put("factory", factory);
        map.put("group", group);
        ApiService.getOperTaskListHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .safeSubscribe(new RxObserver<ResponseData<AppOperationGuideMode>>() {
                    @Override
                    public void _onNext(ResponseData<AppOperationGuideMode> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {

                            total = retData.data.total;
                            adapterList.addAll(retData.data.items);

                            if (isRefreshOrLoadMore == 1) {
                                page = page + 1;
                                tipWizardListAdapter.loadMoreComplete();
                            }
                            if (adapterList.size() == 0) {
                                rlIsnull.setVisibility(View.VISIBLE);
                            } else {
                                rlIsnull.setVisibility(View.INVISIBLE);
                            }
                            tipWizardListAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {

                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srInspection.setRefreshing(false);
                    }
                });


    }


    /**
     * 显示操作进度
     */
    private void preShowProgressDialog(int position) {
        showWaitingDialog("正在获取数据");
        ApiService.getGuideTree(adapterList.get(position).workTaskId)
                .compose(RxSchedulersHelper.io_main())
                .safeSubscribe(new RxObserver<ResponseData<ArrayList<TreeNode>>>() {
                    @Override
                    public void _onNext(ResponseData<ArrayList<TreeNode>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            backList.clear();
                            treeToList(retData.data, backList);
                            AppOperationGuideMode.ItemsBean node = adapterList.get(position);
                            showProgressDialog(node);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();

                    }
                });

    }

    private void showProgressDialog(AppOperationGuideMode.ItemsBean itemsBean) {
        showProgressDialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_tip_wizard_progress, false)
                .show();
        View customView = showProgressDialog.getCustomView();
        RecyclerView rv_progress = customView.findViewById(R.id.rv_progress);
        tipWizardProgressAdapter = new TipWizardProgressAdapter();
        rv_progress.setLayoutManager(new LinearLayoutManager(this));
        rv_progress.setAdapter(tipWizardProgressAdapter);
        tipWizardProgressAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                TreeNode node = (TreeNode)adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.look_btn://查看
                        Intent intent = new Intent(TipWizardListActivity.this, TipWizardWorkActivity.class);
                        intent.putExtra("stepIndexId", node.current.id);
                        intent.putExtra("data", itemsBean);
                        startActivity(intent);
                        showProgressDialog.dismiss();
                        break;
                    case R.id.tv_complete://完成

                        if (!node.current.completed) {//未完成
                            if (isLast(backList)) {//最后一个
                                showFinishDialog(itemsBean.workTaskId,node.current.id);
                            } else {
                                taskStepComplete(itemsBean.workTaskId,node.current.id,false);
                            }
                        }
                        break;
                }
            }
        });
        tipWizardProgressAdapter.setNewData(backList);

    }

    private void updateIndex(int position,boolean isLast) {
        showWaitingDialog("正在获取数据");
        ApiService.getGuideTree(adapterList.get(position).workTaskId)
                .compose(RxSchedulersHelper.io_main())
                .safeSubscribe(new RxObserver<ResponseData<ArrayList<TreeNode>>>() {
                    @Override
                    public void _onNext(ResponseData<ArrayList<TreeNode>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            backList.clear();
                            treeToList(retData.data, backList);
                            AppOperationGuideMode.ItemsBean node = adapterList.get(position);
                            tipWizardProgressAdapter.setNewData(backList);
                            //最后一个
                            if (isLast) {
                                taskComplete(node.workTaskId,node.equipmentTypeId,node.guideType);
                            }
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();

                    }
                });

    }

    /**
     * 任务步骤完成
     */
    private void taskStepComplete(int workTaskId,int stepDetailId,boolean isLast){
        ApiService.tipwizardTaskStepComplete(workTaskId,stepDetailId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("完成中...");
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000) {
                            //刷新列表
                            updateIndex(currentPos,isLast);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void showFinishDialog(int workTaskId,int stepDetailId){
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.layout_work_finish, false)
                .show();
        dialog.findViewById(R.id.confirm_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                taskStepComplete(workTaskId,stepDetailId,true);
            }
        });

        dialog.findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void showGoodDialog(int equipmentTypeId,String guideType){
        if (showProgressDialog != null) {
            showProgressDialog.dismiss();
        }
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.layout_good, false)
                .show();
        dialog.findViewById(R.id.good_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                doGood(equipmentTypeId,guideType);
                EventBus.getDefault().post(new RefreshData());
            }
        });
        dialog.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                EventBus.getDefault().post(new RefreshData());
            }
        });
        dialog.setCanceledOnTouchOutside(false);
    }

    private void doGood(int equipmentTypeId,String guideType){
        showWaitingDialog("正在获取数据");
        ApiService.doGood(equipmentTypeId,guideType)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000 ) {
                            ToastUtils.showShort(TipWizardListActivity.this,"谢谢您的点赞！");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }


    private void taskComplete(int workTaskId,int equipmentTypeId,String guideType){
        showWaitingDialog("正在获取数据");
        ApiService.taskComplete(workTaskId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<Integer>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<Integer> retData) {
                        if (retData.retCode == 10000) {
                            showGoodDialog(equipmentTypeId,guideType);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    /**
     * 判断是否为最后完成项
     * @param backList
     */
    private boolean isLast(ArrayList<TreeNode> backList) {

        int num = 0;
        for (TreeNode node : backList) {
            if (node.current.completed) {
                num++;
            }
        }
        Logger.i("num="+num+"  size:"+backList.size()+"  "+backList);
        if (num >= backList.size() - 1) {
            return true;
        }
        return false;
    }

    private void treeToList(ArrayList<TreeNode> paraList, ArrayList<TreeNode> backList) {
        for (TreeNode node : paraList) {
            backList.add(node);
            if (node.children != null) {
                treeToList(node.children, backList);
            }
        }

    }

    /**
     * 生成二维码
     */
    private void showGenerateDialog(int index) {
        AppOperationGuideMode.ItemsBean node = adapterList.get(index);
        QRScanBean bean = new QRScanBean();
        Gson gson = new Gson();
        bean.json = gson.toJson(node.getGuideQR());
        bean.sceneType = 1;
        bean.token = PrefUtils.getString(MyApp.getmContext(), AppConstant.TOKEN_KEY, "-1");
        String json = gson.toJson(bean);
        Intent intent = new Intent(context, GenerateQRcodeActivity.class);
        intent.putExtra("QRcode", json);
        startActivity(intent);

//        new AsyncTask<Void, Void, Bitmap>() {
//            @Override
//            protected Bitmap doInBackground(Void... params) {
//                return QRCodeEncoder.syncEncodeQRCode(json, BGAQRCodeUtil.dp2px(TipWizardListActivity.this, 150));
//            }
//
//            @Override
//            protected void onPostExecute(Bitmap bitmap) {
//                if (bitmap != null) {
//                    Dialog dialog = new Dialog(TipWizardListActivity.this);
//                    dialog.setContentView(R.layout.custome_generate_qrcode);
//                    dialog.show();
//                    Window dialogWindow = dialog.getWindow();
//                    WindowManager m = TipWizardListActivity.this.getWindowManager();
//                    Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
//                    WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
//                    p.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.65，根据实际情况调整
//                    p.height = p.width;
//                    dialogWindow.setAttributes(p);
//                    ImageView iv_qr_code = dialog.findViewById(R.id.iv_qr_code);
//                    iv_qr_code.setImageBitmap(bitmap);
//                } else {
//                    Toast.makeText(TipWizardListActivity.this, "生成二维码失败", Toast.LENGTH_SHORT).show();
//                }
//
//            }
//        }.execute();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshData event) {
        refreshData();
    }


    @Override
    protected void onDestroy() {
        EventBus eb = EventBus.getDefault();
        if (eb.isRegistered(this)) {
            eb.unregister(this);
        }
        super.onDestroy();
    }

    private void getQueryLocationBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            locationList.clear();
                            companyList.clear();
                            factoryList.clear();
                            childList.clear();
                            locationList.add(new RouteQueryBean("", "", "全部"));
                            locationList.addAll(retData.data);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


}
